import uvicorn
from fastapi import FastAPI, Query, Path, Body
import gradio as gr

fastapi_app = FastAPI()

# 原有的路由
@fastapi_app.get("/chat")
def read_main():
    return {"message": "This is your main app"}

# 新增路由：返回静态数据
@fastapi_app.get("/about")
def about():
    return {"app_name": "FastAPI with Gradio", "version": "1.0"}

# 新增路由：处理查询参数
@fastapi_app.get("/items/")
def read_item(item_id: int = Query(..., title="Item ID", description="The ID of the item to get")):
    return {"item_id": item_id}

# 新增路由：处理路径参数
@fastapi_app.get("/users/{user_id}")
def read_user(user_id: int = Path(..., title="User ID", description="The ID of the user to get")):
    return {"user_id": user_id}

# 新增路由：接收请求体
@fastapi_app.post("/post-data/")
def post_data(data: dict = Body(..., title="Data", description="Data to be processed")):
    return {"received_data": data}

# Gradio 应用
def greet(name: str):
    return "Hello " + name + "!"

with gr.Blocks() as demo:
    name = gr.Textbox(label="Name")
    output = gr.Textbox(label="Output Box")
    greet_btn = gr.Button("Greet")
    greet_btn.click(fn=greet, inputs=name, outputs=output)

# 集成 Gradio 应用到 FastAPI
if __name__ == '__main__':
    app = gr.mount_gradio_app(fastapi_app, demo, path="/")
    uvicorn.run(fastapi_app, port=8001)